package cn.com.xinjinfu.pdoulcProduct;

import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.Toast;

import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;

import java.util.Map;

import cn.com.xinjinfu.pdoulcProduct.activity.base.BaseActivity;
import cn.com.xinjinfu.pdoulcProduct.activity.login.CheckMobileActivity;
import cn.com.xinjinfu.pdoulcProduct.common.ConstantValues;
import cn.com.xinjinfu.pdoulcProduct.engine.DataHandler;
import cn.com.xinjinfu.pdoulcProduct.entity.User;
import cn.com.xinjinfu.pdoulcProduct.fragment.HomeFragment;
import cn.com.xinjinfu.pdoulcProduct.fragment.FindFragment;
import cn.com.xinjinfu.pdoulcProduct.fragment.MyPdouFragment1;
import cn.com.xinjinfu.pdoulcProduct.manager.AccountManager;
import cn.com.xinjinfu.pdoulcProduct.manager.JSONManager;
import cn.com.xinjinfu.pdoulcProduct.manager.L;
import cn.com.xinjinfu.pdoulcProduct.utils.titleBar.DeviceUtils;
import cn.com.xinjinfu.pdoulcProduct.utils.SharedPreferencesUtils;
import cn.com.xinjinfu.pdoulcProduct.utils.SystemBarTintManager;
import cn.com.xinjinfu.pdoulcProduct.view.MyTabWidget;


public class MainActivity extends BaseActivity implements MyTabWidget.OnTabSelectedListener {
    private final String mPageName = "首页";
    private RequestQueue queue;
    private MyTabWidget mTabWidget;
    private HomeFragment mHomeFragment;
    private FindFragment mFindFragment;
    private MyPdouFragment1 mMyPdouFragment;
    private int mIndex = ConstantValues.HOME_FRAGMENT_INDEX;
    private int RETURN_LOGIN = ConstantValues.RETURN_CHECKMOBILE_CODE;
    private FragmentManager mFragmentManager;
    private int versionCode;
    private long exitTime = 0;
    private static String NEWSID = "-1";
    public static final int NOTIFY_ID = 100;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN){
            if((System.currentTimeMillis()-exitTime) > 2000){
                Toast.makeText(getApplicationContext(), "再按一次退出应用程序", Toast.LENGTH_SHORT).show();
                exitTime = System.currentTimeMillis();
            } else {
                //退出代码
                this.finish();
                System.exit(0);
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        init();
        initEvents();
        //注册广播
        registerBoradcastReceiver();
        try {
            PackageInfo pkg = getPackageManager().getPackageInfo(getApplication().getPackageName(), 0);
            versionCode = pkg.versionCode;//版本号比较服务器用
        } catch (NameNotFoundException e1) {
            e1.printStackTrace();
        }

        //检查更新
        queue = Volley.newRequestQueue(this);
        Map<String, String> paraMap = DataHandler.getNewParameters("1410");
        JsonObjectRequest request = new JsonObjectRequest(DataHandler.getBuildUrl(paraMap), null, succeedRespon, null);
        queue.add(request);
        //发现页有新消息时，红点提示；2017.2.24取消
//        findRequest();

        //设置状态栏和导航栏透明  默认为透明
        setStatusBarTranslucent();
        setNavigationBarTranslucent();
    }
    private SystemBarTintManager tintManager;
    /**
     * 设置状态栏颜色
     * @param colorResId
     */
    public void setStatusBarColor(int colorResId){
        if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.KITKAT){
            //如果状态栏管理变量为空则创建
            if(tintManager==null){
                tintManager=new SystemBarTintManager(this);
            }
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);

            // 激活状态栏设置
            tintManager.setStatusBarTintEnabled(true);
//            tintManager.setStatusBarTintColor(ContextCompat.getColor(this, colorResId));
        }
    }

    /**
     * 设置状态栏为透明
     */
    private void setStatusBarTranslucent(){
        if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.KITKAT){
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        }
    }

    /**
     * 设置导航栏颜色
     * @param colorResId
     */
    public void setNavigationBarColor(int colorResId){
        if (DeviceUtils.checkDeviceHasNavigationBar(this)){
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                // 创建状态栏的管理实例
                if(tintManager==null){
                    tintManager = new SystemBarTintManager(this);
                }
                this.getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
                // 激活导航栏设置
                tintManager.setNavigationBarTintEnabled(true);
//                tintManager.setNavigationBarTintColor(ContextCompat.getColor(this, colorResId));
            }
        }
    }

    /**
     * 设置导航栏透明
     */
    private void setNavigationBarTranslucent(){
        if (DeviceUtils.checkDeviceHasNavigationBar(this)){
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                this.getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
            }
        }
    }

    public int getStatusBarHeight() {
        int result = 0;
        int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
        if (resourceId > 0) {
            result = getResources().getDimensionPixelSize(resourceId);
        }
        return result;
    }



    /**
     * 发现页面 中信息提示 是否 显示的网络请求
     */
//    private void findRequest() {
//        if (SharedPreferencesUtils.getOfficialId(this, "officialListMaxId") != "") {
//            NEWSID = SharedPreferencesUtils.getOfficialId(this, "officialListMaxId");
//        }
//        final Map<String, String> parameters = DataHandler.getParameters("1421");
//        parameters.put("newsId", NEWSID);
//        JsonObjectRequest request = new JsonObjectRequest(DataHandler.getBuildUrl(parameters), null,
//                new Response.Listener<org.json.JSONObject>() {
//            @Override
//            public void onResponse(org.json.JSONObject jobj) {
//                if(JSONManager.getError(jobj) == -1){
//                    ishindder(JSONManager.getInt(jobj, "newsNumber") > 0,1);
//                }
//            }
//        }, null);
//        queue.add(request);
//    }

    public void init() {
        mFragmentManager = getSupportFragmentManager();
        mTabWidget = (MyTabWidget) findViewById(R.id.tab_widget);
    }

    private void initEvents() {
        mTabWidget.setOnTabSelectedListener(this);}

    private Response.Listener<org.json.JSONObject> succeedRespon = new Response.Listener<org.json.JSONObject>() {
        @Override
        public void onResponse(org.json.JSONObject jobj) {
            if(JSONManager.getError(jobj) == -1){
                int version = JSONManager.getInt(jobj, "appVersion");
                Log.v("dddd", "版本号返回---" + jobj.toString() + "---versionCode---" + versionCode);
                if(version > versionCode){
//                    UpdateManager manager = new UpdateManager(MainActivity.this,"0");
                    UpdateManager manager = new UpdateManager(MainActivity.this,JSONManager.getString(jobj, "isForceUpData"));
                    manager.checkUpdate(version , "url");
                }
                if(JSONManager.getString(jobj,"isServiceMaintain").equals("1")){    //服务器维护中
                    final Dialog dialog = new Dialog(mContext, R.style.Fill);
                    dialog.setContentView(R.layout.isservicedialog);
                    dialog.findViewById(R.id.exit_button).setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            // 退出
                            MainActivity.this.finish();
                        }
                    });
                    dialog.show();
                    dialog.setCanceledOnTouchOutside(false);
                    dialog.setCancelable(false);
                }
            }
        }
    };


    /***
     * 接受的做任务的广播，选择首页对应的栏目
     */
    private final String ACTION_NAME = "跳转首页广播";
    private String action0 = "";
    public void registerBoradcastReceiver() {
        IntentFilter myIntentFilter = new IntentFilter();
        myIntentFilter.addAction(ACTION_NAME);
        //注册广播
        registerReceiver(mBroadcastReceiver, myIntentFilter);
    }
    private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver(){
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            action0 = intent.getStringExtra("yaner");
            if(action.equals(ACTION_NAME)){
                // 设置当前跳转到第一个Fragment
                if (action0.equals("transfer")){
                    mIndex = ConstantValues.HOME_FRAGMENT_INDEX;
                    mHomeFragment.setIndeticViewPage(1);
                }else if (action0.equals("mPdou")){
                    mIndex = ConstantValues.MYPDOU_FRAGMENT_INDEX;
                }else {
                    mIndex = ConstantValues.HOME_FRAGMENT_INDEX;
                    mHomeFragment.setIndeticViewPage(0);
                }
                onTabSelected(mIndex);
                mTabWidget.setTabsDisplay(mIndex);
            }
        }
    };


    @Override
    protected void onResume() {
        super.onResume();
        onTabSelected(mIndex);
        mTabWidget.setTabsDisplay(mIndex);
//        showNewInfoCount();
    }

    @Override
    public void onTabSelected(int index) {
        FragmentTransaction transaction = mFragmentManager.beginTransaction();
        hideFragments(transaction);
        switch (index) {
            case ConstantValues.HOME_FRAGMENT_INDEX:
                if (null == mHomeFragment) {
                    mHomeFragment = new HomeFragment();
                    transaction.add(R.id.center_layout, mHomeFragment);
                } else {
                    transaction.show(mHomeFragment);
                    if (!action0.equals("transfer")) {//从任务页跳转到home界面，跳转到他人转让列表
                        mHomeFragment.initData();//home的数据刷新
                    }
                }
                break;
            case ConstantValues.FIND_FRAGMENT_INDEX:
                if (null == mFindFragment) {
                    mFindFragment = new FindFragment();
                    transaction.add(R.id.center_layout, mFindFragment);
                } else {
                    transaction.show(mFindFragment);
//                    mFindFragment.loginLoad();
//                    ishindder(mFindFragment.isHidden,1);
                }
                break;
            case ConstantValues.MYPDOU_FRAGMENT_INDEX:
                User user = AccountManager.getInstance().getUser();
                if (user != null) {
                    if (user.getCurrUser().isLogged()) {
                        if (null == mMyPdouFragment) {
                            mMyPdouFragment = new MyPdouFragment1();
                            transaction.add(R.id.center_layout, mMyPdouFragment);
                        } else {
                            transaction.show(mMyPdouFragment);
                            mMyPdouFragment.loginRequest();
                        }
                    }
                } else {
                    Intent intent = new Intent(MainActivity.this,CheckMobileActivity.class);
                    startActivityForResult(intent, RETURN_LOGIN);
                }
                break;
            default:
                break;
        }
        mIndex = index;
        transaction.commitAllowingStateLoss();
    }

    private void hideFragments(FragmentTransaction transaction) {
        if (null != mHomeFragment) {
            transaction.hide(mHomeFragment);
        }
        if (null != mFindFragment) {
            transaction.hide(mFindFragment);
        }
        if (null != mMyPdouFragment) {
            transaction.hide(mMyPdouFragment);
        }
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        // 自己记录fragment的位置,防止activity被系统回收时，fragment错乱的问题
        outState.putInt("index", mIndex);
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        // super.onRestoreInstanceState(savedInstanceState);
        mIndex = savedInstanceState.getInt("index");
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        L.i("MainActivity", "requestCode:"+requestCode+"resultCode:"+resultCode);
        if(resultCode == ConstantValues.BACK_MAIN_RESULTCODE){
            if(requestCode == RETURN_LOGIN){
                mIndex = data.getExtras().getInt("mIndex");
            }
        }
    }
    public void ishindder(boolean cc,int x){
        if (cc){
            mTabWidget.setIndicateDisplay(MainActivity.this, x, true);
        }else {
            mTabWidget.setIndicateDisplay(MainActivity.this, x, false);
        }
    }


//    /***
//     * 新消息icon图标数字提示提示
//     */
//    public void showNewInfoCount(){
//        try {
//            final int count = 1;
//            //自定义消息通知栏
//            NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(getApplicationContext())
//                    .setSmallIcon(getApplicationInfo().icon)
//                    .setWhen(System.currentTimeMillis())
//                    .setAutoCancel(true);
//
//            mBuilder.setContentTitle("test");
//            mBuilder.setTicker("test");
//            mBuilder.setContentText("test");
//
//            //app退到桌面等待3s看效果（有的launcher当app在前台设置未读数量无效）
//            final Notification notification = mBuilder.build();
//            new Handler(getMainLooper()).postDelayed(new Runnable() {
//                @Override
//                public void run() {
//                    BadgeUtil.sendBadgeNotification(notification, NOTIFY_ID, getApplicationContext(), count, count);
//                    Toast.makeText(getApplicationContext(), "success", Toast.LENGTH_SHORT).show();
//                }
//            }, 5 * 1000);
//
//        } catch (NumberFormatException e) {
//            e.printStackTrace();
//        }
//    }

}
